<template>
	<view class="container flex_C">
		<FeNavbar :isBack="false">
			<view class="nav-slot-left" slot="left">
				<view class="tab-item" :class="currentTab == index ? 'tab-active' : ''" v-for="(item,index) in tabs"
					:key="index" @click.stop="handleItemEvent({action:'tabsEvent',index})">
					{{item}}
					<view class="tab-underline" v-if="currentTab == index"></view>
				</view>
			</view>
			<view class="nav-slot-right" slot="right" @click.stop="handleItemEvent({action:'navRightBtn'})">
				<view class="child-name van_ellipsis">{{selectChildAccount || "未选择"}}</view>
				<image :class="showSheet ? 'selecticon-top' : ''" src="@/static/order/select-icon.png"
					mode="aspectFill">
				</image>
			</view>
		</FeNavbar>
		<swiper class="swiper-wrap" :current="currentTab" @change="animationfinish">
			<swiper-item>
				<z-paging :fixed="false" ref="pagingOne" v-model="nowOrderData" :auto="false" @query="reqList"
					:auto-show-system-loading="false" :show-refresher-when-reload="true" :auto-show-back-to-top="true">
					<template #top>
						<view class="section-top-btn on-key-clear" style="width: 234rpx;"
							@click="handleItemEvent({action:'onKeyClear'})">
							<image src="/static/order/clear.png" mode="aspectFill"></image>
							<text>一键平仓</text>
						</view>
					</template>
					<orderItem :datas="nowOrderData" scene="order" />
				</z-paging>
			</swiper-item>
			<swiper-item>
				<z-paging :fixed="false" ref="pagingTwo" v-model="historyOrderData" @query="reqHistoryList"
					:auto="false" :auto-show-system-loading="false" :show-refresher-when-reload="true"
					:auto-show-back-to-top="true">
					<template #top>
						<view class="picker-btn-wrap flexV">
							<view class="picker-btn flexV" @click="handleItemEvent({action:'showStartDate'})">
								<text class="text">{{startDate?''+startDate : "选择起始日期"}}</text>
								<image @click.stop="clearDate('start')" v-if="startDate" class="icon"
									src="/static/common/close_icon.png" />
							</view>
							<text class="lin"></text>
							<view class="picker-btn flexV" @click="handleItemEvent({action:'showEndDate'})">
								<text class="text">{{endDate?''+endDate : "选择终止日期"}}</text>
								<image @click.stop="clearDate('end')" v-if="endDate" class="icon"
									src="/static/common/close_icon.png" />
							</view>
						</view>
					</template>
					<orderItem :datas="historyOrderData" scene="history" />
				</z-paging>
			</swiper-item>
		</swiper>

		<u-datetime-picker :minDate="946656000000" :maxDate="startDateMax" :show="startDatetimePickerShow"
			v-model="defaultDate" mode="date" @cancel="startDatetimePickerShow = false"
			@confirm="handleStartDatePickerConfirm" confirmColor="#FFE269"></u-datetime-picker>

		<u-datetime-picker :minDate="endDateMin" :maxDate="maxDate" :show="endDatetimePickerShow" v-model="defaultDate"
			mode="date" @cancel="endDatetimePickerShow = false" @confirm="handleEndDatePickerConfirm"
			confirmColor="#FFE269"></u-datetime-picker>

		<!-- 子账号选择 -->
		<u-picker :closeOnClickOverlay="true" :defaultIndex="defaultIndex" :show="pickerShow" keyName="subAccountName"
			:columns="childList" confirmColor="#FFE269" @cancel="pickerShow = false"
			@confirm="handlePickerConfirm"></u-picker>

		<!-- 一键平仓 -->
		<onKeyClearPanel ref="refOnKeyClearPanel" @complete="handleClearComplete" />
	</view>
</template>

<script>
	const navHeight = uni.upx2px(88) + uni.getSystemInfoSync().statusBarHeight;
	import orderItem from "./components/orderItem.vue"
	import tabs from "@/components/tabs/tabs.vue"
	import Skeleton from '@/components/skeleton/index.vue';
	import onKeyClearPanel from '@/components/onKeyClearPanel/onKeyClearPanel.vue'
	import {
		listApi
	} from '@/api/subAccount.js'
	import {
		childOrderNow,
		childOrderHistory
	} from "@/api/order.js"

	export default {
		components: {
			orderItem,
			tabs,
			onKeyClearPanel,
			Skeleton
		},
		data() {
			return {
				navHeight,
				navOpacity: 1,
				currentTab: 0,
				tabs: ["当前订单", "历史订单"],

				nowOrderData: [], // 当前订单
				historyOrderData: [], // 历史订单
				historyLoad: false,

				showSheet: false,

				startDatetimePickerShow: false,
				endDatetimePickerShow: false,
				defaultDate: new Date().getTime(),
				maxDate: new Date().getTime(),
				endDateMin: 946656000000,
				startDateMax: new Date().getTime(),

				startDate: "",
				endDate: "",

				pickerShow: false,
				selectChildAccount: "", // 选择的子账号
				childList: [
					[]
				],
				defaultIndex: [
					[0]
				],
				subAccountId: null, // 当前选择的子账号id
				isFirst: true,
				isLoadSubAccountApi: false, // 是否成功请求过子账号接口

				isRefresh: true,
				// 记录当前订单跟历史订单上一次请求的子账号id，判断切换的时候是否需要刷新
				currentOrder_childId: null,
				historyOrder_childId: null
			};
		},
		onLoad() {
			const {
				token
			} = uni.getStorageSync("userInfo");
			if (!this.isEmpty(token)) {
				this.reqChildList()
			} else {
				this.hint()
			}
		},
		onShow() {
			if (this.isFirst) {
				this.isFirst = false
				return
			}
			const {
				token
			} = uni.getStorageSync("userInfo");
			if (this.isEmpty(token)) {
				this.hint()
				return
			};
			const isRefresh = uni.getStorageSync('subAccountChange');
			const _changeAccount_refresh_order = uni.getStorageSync("changeAccount_refresh_order");

			// 切换过账号
			if (_changeAccount_refresh_order) {
				this.nowOrderData = [];
				this.historyOrderData = [];
				this.reqChildList();
				uni.removeStorageSync("changeAccount_refresh_order");
				return
			}

			// 未切换过子账号，只刷新订单列表，否则刷新子账号
			if (!isRefresh) {
				this.reload()
				return
			};
			this.reqChildList()
		},
		methods: {
			hint() {
				uni.showModal({
					title: "温馨提示",
					content: "当前您还未登录，是否需要前往登录？",
					confirmText: "去登录",
					cancelText: "再看看",
					success(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						} else {
							uni.switchTab({
								url: '/pages/tabbar/home/home'
							})
						}
					}
				})
			},
			// 获取子账号
			async reqChildList() {
				uni.setStorageSync('subAccountChange', false)
				uni.showLoading({
					mask: true,
					title: '加载中...'
				})
				const result = await listApi();

				this.isLoadSubAccountApi = true;

				uni.hideLoading()
				const {
					subAccounts
				} = result.data
				if (this.isEmpty(subAccounts)) {
					this.childList = [
						[]
					]
					this.selectChildAccount = "";
					this.subAccountId = null;
				} else {
					this.childList = [subAccounts];
					const currentSubAccountId = Number(uni.getStorageSync('currentSubAccountId'));
					const ids = subAccounts.map(item => item.subAccountId)
					let index = ids.indexOf(currentSubAccountId)
					index = index < 0 ? 0 : index
					this.defaultIndex = [
						[index]
					]
					this.subAccountId = ids[index]
					this.selectChildAccount = subAccounts[index].subAccountName
				}
				this.reload()
			},
			reload() {
				this.currentTab ?
					this.$refs.pagingTwo.reload() :
					this.$refs.pagingOne.reload();
			},
			/**
			 * 获取订单列表
			 */
			reqList(pageNo, pageSize) {
				this.currentOrder_childId = this.subAccountId

				const params = {
					limit: pageSize,
					page: pageNo,
				};
				if (!this.isEmpty(this.subAccountId)) {
					params["subAccountId"] = this.subAccountId;
				}

				childOrderNow(params).then(res => {
					this.$refs.pagingOne.complete(res.data.orders);
				}).catch(() => {
					this.$refs.pagingOne.complete(false);
				})

			},

			reqHistoryList(pageNo, pageSize) {
				this.historyOrder_childId = this.subAccountId
				const params = {
					limit: pageSize,
					page: pageNo,
				};

				if (!this.isEmpty(this.subAccountId)) {
					params["subAccountId"] = this.subAccountId;
				}
				if (!this.isEmpty(this.startDate)) {
					params["startDate"] = this.startDate;
				}
				if (!this.isEmpty(this.endDate)) {
					params["endDate"] = this.endDate;
				}
				childOrderHistory(params).then(res => {
					this.historyLoad = true
					this.$refs.pagingTwo.complete(res.data.orders);
				}).catch(() => {
					this.$refs.pagingTwo.complete(false);
				})
			},

			handleItemEvent(vals) {
				const {
					action,
					index
				} = vals;
				switch (action) {
					case "tabsEvent":
						this.currentTab = index;
						break;

					case "navRightBtn":
						if (JSON.stringify(this.childList) == "[[]]") {
							uni.showToast({
								title: "当前账号无子账号",
								icon: "none"
							})
							return
						}
						this.pickerShow = true;

						break;

					case "onKeyClear": // 一键平仓
						if (this.isEmpty(this.nowOrderData)) {
							uni.showToast({
								title: "当前无订单可操作",
								icon: "none"
							})
							return
						}

						this.$refs.refOnKeyClearPanel.show({
							level: "sub_account",
							subAccountId: this.subAccountId
						});

						break;
					case "showStartDate": // 开始日期
						this.startDatetimePickerShow = true;
						break;
					case "showEndDate": // 结束日期
						this.endDatetimePickerShow = true;
						break;
				}
			},

			handleClearComplete() {
				this.$refs.pagingOne.reload();
			},
			handleStartDatePickerConfirm(val) {
				this.startDate = this.momentFormat(val.value, "YYYY-MM-DD");
				this.startDatetimePickerShow = false;
				this.endDateMin = val.value;
				this.$refs.pagingTwo.reload();
			},

			handleEndDatePickerConfirm(val) {
				this.endDate = this.momentFormat(val.value, 'YYYY-MM-DD');
				this.endDatetimePickerShow = false;
				this.startDateMax = val.value
				this.$refs.pagingTwo.reload();
			},

			handlePickerConfirm(vals) {
				this.selectChildAccount = vals.value[0].subAccountName;
				this.subAccountId = vals.value[0].subAccountId;
				this.pickerShow = false;
				this.reload()

			},

			animationfinish(res) {
				const {
					current
				} = res.detail;
				this.currentTab = current;
				if (
					(current == 0 && (this.subAccountId != this.currentOrder_childId)) ||
					(current == 1 && ((this.subAccountId != this.historyOrder_childId) || !this.historyLoad))
				) {
					this.reload()
				}
			},

			clearDate(type) {
				if (type == 'start') {
					this.startDate = '';
					this.endDateMin = 946656000000;
				} else {
					this.endDate = '';
					this.startDateMax = new Date().getTime();
				}
				this.$refs.pagingTwo.reload();
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/ .u-popup {
		position: fixed;
	}

	/deep/ .u-popup__content {
		border-radius: 20rpx 20rpx 0 0;
	}

	.container {
		width: 100%;
		/* #ifdef H5 */
		height: calc(100vh - 50px);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		background-color: #F5F7F8;
		display: flex;
		flex-direction: column;

		.nav-slot-left {
			height: 88rpx;
			line-height: 88rpx;
			display: flex;
			align-items: center;
			background-color: #fff;

			.tab-item {
				height: 100%;
				font-size: 28rpx;
				font-weight: 600;
				color: #A6ACB4;
				padding: 0 22rpx;
				position: relative;
			}

			.tab-active {
				color: $font-color;
				font-size: 34rpx;
			}

			.tab-underline {
				width: 46rpx;
				height: 8rpx;
				background-color: #26282B;
				border-radius: 20rpx 20rpx 0 0;
				position: absolute;
				bottom: 0rpx;
				left: 70rpx;
			}
		}

		.nav-slot-right {
			padding: 20rpx 0;
			display: flex;
			align-items: center;

			.child-name {
				font-size: 28rpx;
				color: $font-color;
				line-height: 33rpx;
				max-width: 260rpx;
			}

			image {
				width: 24rpx;
				height: 24rpx;
				margin-left: 10rpx;
				transition: 0.2s ease;
			}

			.selecticon-top {
				transform: rotate(180deg);
			}
		}



		.swiper-wrap {
			height: 0;
			flex: 1;



			.section-top-btn {
				width: 234rpx;
				height: 68rpx;
				font-size: 28rpx;
				color: #26282B;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 24rpx 0 24rpx 32rpx;
				border-radius: 8rpx;

				image {
					width: 36rpx;
					height: 36rpx;
					margin-right: 20rpx;
				}

				.clear-btn {
					width: 30rpx;
					height: 30rpx;
					background-color: #ddd;
					margin-left: 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.picker-btn-wrap {
				padding: 24rpx 32rpx;

				.lin {
					width: 20rpx;
					height: 2rpx;
					background-color: #A6ACB4;
					margin: 0 20rpx;
				}

				.picker-btn {
					height: 68rpx;
					background: #FFFFFF;
					border-radius: 12rpx;
					padding: 0 16rpx;

					.text {
						font-weight: 400;
						font-size: 26rpx;
						color: #A6ACB4;
					}

					.icon {
						width: 32rpx;
						height: 32rpx;
						margin-left: 16rpx;
					}
				}
			}

			.on-key-clear {
				background-color: #FBD536;
			}

			.date-filter {
				background-color: #ffffff;
			}
		}

		.slot-nav-left {}

		.slot-nav-right {
			display: flex;
			align-items: center;
			height: 100%;

			.child-name {
				font-size: 26rpx;
				color: #7B828A;
				max-width: 200rpx;
			}

			image {
				width: 24rpx;
				height: 24rpx;
				margin-left: 10rpx;
				transition: 0.2s ease;
			}

			.selecticon-top {
				transform: rotate(180deg);
			}
		}
	}
</style>